/* This program is free software. It comes without any warranty, to
 * the extent permitted by applicable law. You can redistribute it
 * and/or modify it under the terms of the Do What The Fuck You Want
 * To Public License, Version 2, as published by Sam Hocevar. See
 * http://sam.zoy.org/wtfpl/COPYING for more details. */ 
package de.rockon.fuzzy.controller.gui.tree.treehelper;

import java.awt.Component;
import java.awt.FlowLayout;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;

import de.rockon.fuzzy.controller.model.FuzzyBasicElement;
import de.rockon.fuzzy.controller.model.FuzzyPoint;
import de.rockon.fuzzy.controller.model.FuzzySet;
import de.rockon.fuzzy.controller.model.FuzzyVariable;
import de.rockon.fuzzy.controller.model.enums.VariableType;
import de.rockon.fuzzy.controller.util.factories.IconFactory;

public class TreeRenderer extends DefaultTreeCellRenderer {
	private static final long serialVersionUID = -7848719984005986366L;

	@Override
	public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row,
			boolean hasFocus) {
		JPanel colorPanel;
		if (value instanceof FuzzyBasicElement) {

			FuzzyBasicElement val = (FuzzyBasicElement) value;
			String icon = val.getIcon();
			if (value instanceof FuzzyVariable) {
				if (((FuzzyVariable) value).getType() == VariableType.INPUT) {
					icon = IconFactory.ICON_FUZZYSETS_INPUT;
				} else {
					icon = IconFactory.ICON_FUZZYSETS_OUTPUT;
				}
			}
			setIcons(icon);
			if (val instanceof FuzzyPoint) {
				FuzzyPoint val1 = (FuzzyPoint) value;
				value = val1.dump();
			} else {
				value = val.getName() + " [" + val.size() + "]";
			}

			if (val instanceof FuzzySet) {
				colorPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 3, 0));
				colorPanel.setOpaque(false);

				JLabel colorBoxLabel = new JLabel("     ");
				// JLabel colorBoxInfo = new JLabel(""+value);
				colorBoxLabel.setOpaque(true);
				colorBoxLabel.setBackground(((FuzzySet) val).getColorType().getColor());
				colorPanel.add(colorBoxLabel);
				colorPanel.add(super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus));
				// colorPanel.add(colorBoxInfo);
				return colorPanel;
			}
		}

		return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
	}

	private void setIcons(String icon) {
		ImageIcon newIcon = IconFactory.getInstance().getImageIcon(icon);
		setIcon(newIcon);
		setClosedIcon(newIcon);
		setOpenIcon(newIcon);
		setLeafIcon(newIcon);
	}
}